from .checkproxy import CheckProxy
from concurrent.futures import ThreadPoolExecutor
import requests
import config
import time


class HTTPValidator(CheckProxy):

	def check_proxy(self, proxies):
		try:
			start_time = time.time()
			response = requests.get(url = config.test_http_proxy_url, proxies = {'http': proxies['ip_port']},
									timeout = config.time_out)
			end_time = time.time()
			if response.status_code == 200:
				proxies['time'] = (end_time - start_time) * 1000
				self.success_count += 1
				self.data.append(proxies)
				return True
		except Exception as e:
			self.failed_count += 1
		return False

	def batch_check_proxy(self, proxies):
		super().batch_check_proxy(proxies)
		try:
			with ThreadPoolExecutor(max_workers = 24) as executor:
				executor.map(self.check_proxy, proxies)
			self.log.log(self.__class__.__name__,
						 "Success {} data, failure {} data".format(self.success_count, self.failed_count))
		except Exception as e:
			self.log.log(self.__class__.__name__, "Failed to check proxy : {}".format(e))
		return self.data
